<?php
namespace App\Core;

class Router {
    protected static $routes = [];
    protected static $middleware = [];

    // 注册 GET 路由
    public static function get($uri, $callback, $middleware = []) {
        self::$routes['GET'][trim($uri, '/')] = [
            'callback' => $callback,
            'middleware' => $middleware
        ];
    }

    // 注册 POST 路由
    public static function post($uri, $callback, $middleware = []) {
        self::$routes['POST'][trim($uri, '/')] = [
            'callback' => $callback,
            'middleware' => $middleware
        ];
    }

    // 分发请求
    public static function dispatch() {
        $method = $_SERVER['REQUEST_METHOD'];
        $uri = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');

        // 检查路由是否存在
        if (isset(self::$routes[$method][$uri])) {
            $route = self::$routes[$method][$uri];
            $callback = $route['callback'];
            $middleware = $route['middleware'];

            // 执行中间件
            foreach ($middleware as $m) {
                $middlewareInstance = new $m();
                $middlewareInstance->handle();
            }

            // 执行回调
            if (is_callable($callback)) {
                call_user_func($callback);
            } elseif (is_array($callback)) {
                list($controller, $method) = $callback;
                $controllerInstance = new $controller();
                call_user_func([$controllerInstance, $method]);
            }
        } else {
            // 抛出 404 异常
            throw new \Exception("404 Not Found", 404);
        }
    }
}